package com.test.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //过滤内容

        HttpServletRequest request = (HttpServletRequest)servletRequest; //强制转化成 httpservlet的request
        HttpServletResponse response = (HttpServletResponse)servletResponse; //强制转化成 httpservlet的response

        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        String prefixPath = request.getContextPath(); //前缀
        if(username == null){
            System.out.println("我登出了");
            //未登录，跳走
            response.sendRedirect(prefixPath + "/error.jsp");
        }

        //程序继续
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
